<template>
  <div class="m-iselect">
    <span class="name">按省份选择:</span>
    <el-select
      v-model="pvalue"
      placeholder="省份"
    >
      <el-option
        v-for="item in province"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-select
      v-model="cvalue"
      :disabled="!city.length"
      placeholder="城市"
    >
      <el-option
        v-for="item in city"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-autocomplete
      v-model="input"
      :fetch-suggestions="querySearchAsync"
      @select="handleSelect"
      placeholder="请输入城市中文或拼音"
    />
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data () {
    return {
      province: [], // 获取的省份列表
      pvalue: '', // 当前选中的省份
      city: [], // 某省份下城市列表
      cvalue: '', // 当前选中的城市
      input: '', // 城市输入框内容（中文或拼音）
      cities: [] // 全国的城市列表
    }
  },
  watch: { // 监听省份，确定需要展示的城市列表，实现级联效果
    async pvalue (newVal) {
      const { status, data: { city } } = await this.$axios.get(`/geo/province/${newVal}`)
      if (status === 200) {
        this.city = city.map((item) => {
          return {
            value: item.id,
            label: item.name
          }
        })
        this.cvalue = ''
      }
    }
  },
  async created () {
    const { status, data: { province } } = await this.$axios.get('/geo/province')
    if (status === 200) {
      this.province = province.map((item) => {
        return {
          label: item.name,
          value: item.id
        }
      })
    }
  },
  methods: {
    querySearchAsync: _.debounce(async function (query, cb) {
      const self = this
      if (self.cities.length) {
        cb(self.cities.filter(item => item.value.includes(query)))
      } else {
        const { status, data: { city } } = await self.$axios.get('/geo/city')
        if (status === 200) {
          self.cities = city.map((item) => {
            return {
              value: item.name
            }
          })
          cb(self.cities.filter(item => item.value.includes(query)))
        } else {
          // eslint-disable-next-line standard/no-callback-literal
          cb([])
        }
      }
    }, 1000),
    handleSelect (item) {
      this.$store.dispatch('geo/setPosition', {
        province: this.pvalue,
        city: item.value
      })
      this.$router.push('/') // 跳转至首页
    }
  }
}
</script>

<style lang="scss">
  @import "@/assets/css/changeCity/iselect.scss";
</style>
